package cn.idu.socket.sample0410;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;

public class NioBlockingHttpClient {

    SocketChannel socketChannel;

    public static void main(String[] args) {
        NioBlockingHttpClient nioBlockingHttpClient = new NioBlockingHttpClient();
        for (int i = 0; i < 10; i++) {
            nioBlockingHttpClient.request("www.baidu.com", 80);
        }
    }


    public void request(String host, int port) {

        InetSocketAddress remote = new InetSocketAddress(host, port);
        try {
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(true);
            Socket socket = socketChannel.socket();
            socket.setSoTimeout(5000);
            socket.connect(remote);

            PrintWriter writer = getWriter(socket);
            writer.write(conpositeRequest(host));
            writer.flush();

            BufferedReader reader = getReader(socket);
            String msg;
            while ((msg = reader.readLine()) != null) {
                System.out.println("*******: " + msg);
            }
            System.out.println("end");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(inputStream));
    }

    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        return new PrintWriter(new OutputStreamWriter(outputStream));
    }


    private String conpositeRequest(String host) {
        return "GET / HTTP/1.1\r\n " +
                "Host: " + host + "\r\n" +
                "User-Agent: curl/7.43.0\r\n" +
                "Accept: */*\r\n\r\n";
    }
}
